package com.itxiaoxiong.chat.socket;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.RestController;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

@Slf4j
@RestController
public class TcpServer {
    private static final int PORT = 6789;
    private static final HashMap<String, PrintWriter> clientWriters = new HashMap<>();
    private static final ExecutorService pool = Executors.newCachedThreadPool();


    public static void main(String[] args) {
        try (ServerSocket serverSocket = new ServerSocket(PORT)) {
            System.out.println("TCP服务端正在监听端口 " + PORT);

            while (true) {//持续监听客户端的连接请求
                Socket clientSocket = serverSocket.accept();
                System.out.println("新的客户端连接");
                //启动线程
                pool.execute(new ClientHandler(clientSocket));
            }
        } catch (IOException ex) {
            System.out.println("Server exception: " + ex.getMessage());
            ex.printStackTrace();
        }
    }

    private static class ClientHandler implements Runnable {
        private final Socket clientSocket;
        private String userId;
        private PrintWriter out;
        private BufferedReader in;

        public ClientHandler(Socket socket) {
            this.clientSocket = socket;
        }

        @Override
        public void run() {
            try (InputStream input = clientSocket.getInputStream();
                 OutputStream output = clientSocket.getOutputStream();
                 BufferedReader reader = new BufferedReader(new InputStreamReader(input));
                 PrintWriter writer = new PrintWriter(output, true)) {

                this.in = reader;
                this.out = writer;

                userId = reader.readLine();
                System.out.println("write:" + writer);
                System.out.println("收到客户端发来的："+ userId);
                //userId = getUserIdInTcp(userId);
                clientWriters.put(userId, writer);
                System.out.println("User ID: " + userId);

                String text;
                while ((text = reader.readLine()) != null) {
                    System.out.println("接收到的消息 " + userId + ": " + text);
                    //if ()
                    handleMessage(text);
                }

            } catch (IOException ex) {
                System.out.println("客户端连接状态: " + ex.getMessage());
                ex.printStackTrace();
            } finally {
                // 释放
                if (userId != null) {
                    clientWriters.remove(userId);
                }
                try {
                    clientSocket.close();
                } catch (IOException e) {
                    System.out.println("释放失败: " + e.getMessage());
                }
            }
        }
        private void handleMessage(String message) {
            // 解析消息格式
            String[] parts = message.split("#");
            if (parts.length == 5) {
                String fromUserId = parts[0].trim();  // 发送者 ID
                String toUserId = parts[1].trim();    // 接收者 ID或群聊ID
                if (parts[2].equals("qunliao")) {
                    System.out.println("群聊");
                    sendToUser(toUserId,  message);
                } else {
                    sendToUser(toUserId,  message);
                    sendToUser(fromUserId,  message);
                }
            } else {
                System.out.println("消息格式无效: " + message);
             //   clientWriters.clear();//销毁HashMap
            }
        }

        private void sendToUser(String userId, String message) {
            String[] parts = message.split("#");
            if(parts[2].equals("siliao")) {
                //log.error("siliao");
                PrintWriter writer = clientWriters.get(userId);
                if (writer != null) {
                    writer.println(userId + ": " + message);//发给对应的客户端
                } else {
                    System.out.println("这个id没有连接: " + userId);
                }
            } else {
                List<Integer> members = DatabaseUtils.getGroupMembers(Integer.valueOf(parts[1]));
                for (Integer member : members) {
                    PrintWriter writer = clientWriters.get(String.valueOf(member));
                    if (writer != null) {
                        message = parts[0] + "#" + parts[2] + "#" + parts[1] + "#" + parts[3] + "#" + parts[4];
                        writer.println(member + ": " + message);
                    } else {
                        System.out.println("这个id没有连接: " + member);
                    }
                }
            }
        }
    }
    public static void destroyClientWriter(String userId) {
        PrintWriter writer = clientWriters.remove(userId);
        if (writer!= null) {
            writer.close();
        }
    }
}

